<?php

namespace Common\Service;

use Think\Controller;

class DataService extends Controller {

    /**
     * 数据增量保存
     * @param Query|string $dbQuery 数据查询对象
     * @param array $data 需要保存或更新的数据
     * @param string $key 条件主键限制
     * @param array $where 其它的where条件
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function save($dbQuery, $data, $key = 'id', $where = []) {
        $db = is_string($dbQuery) ? M($dbQuery) : $dbQuery;
        $where = array($key => isset($data[$key]) ? $data[$key] : '');
        if (M($db->getTableName())->where($where)->count() > 0) {
            return M($db->getTableName())->strict(false)->where($where)->save($data) !== false;
        }
        return M($db->getTableName())->strict(false)->add($data) !== false;
    }

    /**
     * 更新数据表内容
     * @param Query|string $dbQuery 数据查询对象
     * @param array $where 额外查询条件
     * @return bool|null
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function update($dbQuery, $where = []) {
//        $request = app('request');
        $db = is_string($dbQuery) ? M($dbQuery) : $dbQuery;
        list($pk, $table) = [$db->getPk(), $db->getTableName()];
        list($field, $value) = [I('post.field', ''), I('post.value', '')];
        $where = array(empty($pk) ? 'ids' : $pk => array('in', I('post.id', '')));
        // 删除模式，如果存在 is_deleted 字段使用软删除
        if ($field === 'delete') {
            if (in_array('is_deleted', $db->getDbFields())) {
                return M($table)->where($where)->setField('is_deleted', 0) !== false;
            }
            return M($table)->where($where)->delete() !== false;
        }
        // 更新模式，更新指定字段内容
        return M($table)->where($where)->setField($field, $value) !== false;
    }

}
